package com.cc.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.cc.entity.Answer;
import com.cc.entity.Content;
import com.cc.mongo.MongoDao;
import com.cc.mongo.Questions;
import com.cc.mongo.StatisticalItem;

@Service
public class QuestionsService {
	@Resource  
    private MongoDao mongoDao;
	
	public List<Questions> queryByidList(List<String> questionids){
		List<Questions> record=mongoDao.query(Criteria.where("id").in(questionids));
		return record;
	}
	
	public int handelAnswer(Answer answer){
		String questionsid=answer.getQuestionsid();
		Query query = Query.query(Criteria.where("id").is(questionsid));
		Questions target=mongoDao.query(Criteria.where("id").is(questionsid)).get(0);
		for(int i=0;i<answer.getContent().size();i++){
			Content item=answer.getContent().get(i);
			if((item.getChoosen()==null||item.getChoosen().size()==0)&&(item.getAnswer()==null||item.getAnswer().trim().equals("")))
				continue;
			int index=item.getIndex();
			com.cc.mongo.Content answertarget= this.getTargetContentByindex(index,target.getContent());
			if(item.getType()!=2)//单选
			{
				List<Integer> chooselist=item.getChoosen();
				for(int j=0;j<answertarget.getStatistical().size();j++){
					StatisticalItem one=answertarget.getStatistical().get(j);
					for(int k=0;k<chooselist.size();k++){
						if(one.getIndex()==chooselist.get(k)) one.setTotal(one.getTotal()+1);
							
					}
					
				}
			}else{
				String anstxt= item.getAnswer();
				answertarget.getAnswer().add(anstxt);
			}
			
		}
		mongoDao.save(target);
		return 0;
	}
	
	public com.cc.mongo.Content getTargetContentByindex(int index,List<com.cc.mongo.Content> record){
		com.cc.mongo.Content result=null;
		for(com.cc.mongo.Content one :record){
			if(one.getIndex()==index) result=one;
		}
		return result;
	}

}
